package com.chensf.studydemo.common.query

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chensf.studydemo.R
import com.chensf.studydemo.common.MediaGridInset
import com.chensf.studydemo.inflate
import kotlinx.android.synthetic.main.fragment_grid_image.*
import kotlinx.android.synthetic.main.view_grid_image_item.view.*

class GridImageDemo :Fragment(){
    private lateinit var adapter: GridImageAdapter
    private val data = arrayOf(
        R.drawable.test1,
        R.drawable.test2,
        R.drawable.test3,
        R.drawable.test4,
        R.drawable.test5,
        R.drawable.test6,
        R.drawable.test7,
        R.drawable.test8,
        R.drawable.test9,
        R.drawable.test10,
        R.drawable.test11,
        R.drawable.test12,
        R.drawable.test13,
        R.drawable.test14,
        R.drawable.test15,
        R.drawable.test16,
        R.drawable.test17
    )
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_grid_image,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = GridImageAdapter()
        adapter.data.addAll(data)
        recyclerView.layoutManager = GridLayoutManager(requireContext(),3)
        recyclerView.addItemDecoration(MediaGridInset(3,20,false))
        recyclerView.adapter = adapter
    }

    class GridImageAdapter:RecyclerView.Adapter<GridImageHolder>(){
        val data = mutableListOf<Int>()
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GridImageHolder {
           return GridImageHolder(parent.inflate(R.layout.view_grid_image_item))
        }

        override fun onBindViewHolder(holder: GridImageHolder, position: Int) {
            val item = data[position]
            Glide.with(holder.itemView)
                .load(item)
                .override(200,200)
                .centerCrop()
                .into(holder.imageView)
        }

        override fun getItemCount(): Int {
           return data.size
        }

    }
    class GridImageHolder(itemView: View) :RecyclerView.ViewHolder(itemView){
        val imageView:ImageView = itemView.imageView
    }
}